﻿using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;

namespace NMbsDuplex.TCPServerX.Pinner
{
    using Deamon;
    using Node;
    using System.Threading.Tasks;

    public delegate void workerInjection(Queue<NodesUser> messageQueueCopy);

    public sealed class Pinner : TCPBase
    {
        // 客户端的实现 快速返回父类消息队列
        public Queue<NodesUser> msgQueue4WPF { get { return base.MsgQueue; } }
        public volatile bool isFired;
        public volatile workerInjection _workBlockCopy;

        public bool WPFSockDisConnect()
        {
            Listener.QosSend(Tokenizer.TFin + "WPF客户端退出~");

            int N = -1;
            if(Listener.QosRecv(ref N) != string.Empty)
            {
                Listener.Close();
            }

            isFired = false;
            return isFired;
        }
        public Pinner(Int32 port, workerInjection block) : base(port)
        {
            System.Threading.Thread.Sleep(1777);
            Listener.Connect(IPAddress.Loopback, port);

            if (Listener.Connected)
            {
                // 0.首次连接服务器端 接受一次控制台欢迎字符串
                this.isFired = true;
                _workBlockCopy = block;

                Ping1st();

                // 1.开启不间断心跳包发送模式
                Task.Run(() =>
                {
                    while (isFired)
                    {
                        // 掉用外部注入的函数指针
                        Ping4Ever();
                    }
                });
            }
            else { throw new Exception("Sock客户端Poll 服务器端失败"); }
        }

        private void Ping1st()
        {
            /* 从函数池抓取一个处理tcp字节流函数: 这里是[用户链表节点增长] */
            DuplexEvent TCPMsgHandler = RegisterDict4Domain[CoreInjector.NodeLargen];
            TCPMsgHandler(Listener);
            int N1 = -1;
            var recv = Listener.QosRecv(ref N1);
            base.FindRoadMap(Listener, recv);
            _workBlockCopy?.Invoke(base.MsgQueue);
        }

        private void Ping4Ever()
        {
            // 推送函数 使用Sock初始化设置的编码 这里为Utf8
            System.Threading.Thread.Sleep(1000 * 1);

            if (DateTime.Now.Second % 3 == 0) 
            {
                string fileMsg = Tokenizer.TFile;
                Listener.QosSend(fileMsg);
                drain_from_socket_pipe_i_mean_itsJust_a_queue();
            }
            else if (DateTime.Now.Second % 1 == 0)
            {
                string pingMsg = Tokenizer.TPIN + DateTime.Now.ToString();
                Listener.QosSend(pingMsg);
                // drain_from_socket_pipe_i_mean_itsJust_a_queue();
            }
        }
        private void drain_from_socket_pipe_i_mean_itsJust_a_queue()
        {
            int N = -1;
            var ServMsg = Listener.QosRecv(ref N);
            base.FindRoadMap(Listener, ServMsg);
            _workBlockCopy?.Invoke(base.MsgQueue);
        }
    }
}
